<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="团队名称" prop="teamName">
        <el-input v-model="queryParams.teamName" placeholder="请输入团队名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['commgr:team:add']">新增团队</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['commgr:team:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['commgr:team:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['commgr:team:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="teamList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="团队编号" align="center" prop="teamId" width="80" />
      <el-table-column label="团队名称" align="center" prop="teamName" min-width="200" />
      <el-table-column label="团队成员" align="center" width="300">
        <template slot-scope="scope">
          <div v-if="scope.row.members && scope.row.members.length > 0">
            <div v-for="member in scope.row.members" :key="member.userId" class="member-item">
              <span>{{ member.nickName || member.userName }}</span>
              <el-tag size="mini" :type="getMemberTypeTagType(member.teamType)" style="margin-left: 5px;">
                {{ getMemberTypeLabel(member.teamType) }}
              </el-tag>
            </div>
          </div>
          <span v-else class="text-muted">暂无成员</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['commgr:team:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-user" @click="handleViewMembers(scope.row)"
            v-hasPermi="['commgr:team:edit']">管理成员</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['commgr:team:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改团队对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="团队名称" prop="teamName">
          <el-input v-model="form.teamName" placeholder="请输入团队名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 团队成员管理对话框 -->
    <el-dialog title="团队成员管理" :visible.sync="membersOpen" width="900px" append-to-body class="team-members-dialog">
      <div class="team-detail">
        <!-- 权限提示 -->
        <div v-if="hasManagementPermission === false" class="permission-alert">
          <el-alert title="权限不足" type="warning" description="只有团队的第一位指导老师才能管理团队成员和奖金分配" :closable="false" show-icon>
          </el-alert>
        </div>

        <!-- 团队头部信息 -->
        <div class="team-header">
          <h3 class="team-title">{{ currentTeam.teamName }}</h3>

          <!-- 权限提示信息 -->
          <div v-if="hasManagementPermission === false" class="permission-info">
            <el-tag type="warning">只读模式</el-tag>
            <span class="permission-tips">您没有管理权限，只能查看信息</span>
          </div>

          <!-- 奖金分配信息 -->
          <div class="bonus-info" v-if="bonusData">
            <!-- 奖金卡片 -->
            <el-row :gutter="20" class="bonus-cards">
              <el-col :span="8">
                <el-card class="bonus-card" shadow="hover">
                  <div class="bonus-card-content">
                    <div class="bonus-title">指导团队奖金</div>
                    <div class="bonus-amount instructor-color">
                      ¥{{ formatMoney(bonusData.instructor_bonus) }}
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card class="bonus-card" shadow="hover">
                  <div class="bonus-card-content">
                    <div class="bonus-title">参赛团队奖金</div>
                    <div class="bonus-amount participant-color">
                      ¥{{ formatMoney(bonusData.participant_bonus) }}
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card class="bonus-card" shadow="hover">
                  <div class="bonus-card-content">
                    <div class="bonus-title">总奖金</div>
                    <div class="bonus-amount total-color">
                      ¥{{ formatMoney(bonusData.total_bonus) }}
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>

            <!-- 获奖信息 -->
            <div class="award-info">
              <el-alert v-if="bonusData.award_status === '已获奖'"
                :title="`获奖信息：${bonusData.competition_name} - ${bonusData.com_item_name} - ${bonusData.award_level}`"
                type="success" :closable="false" show-icon>
              </el-alert>
              <el-alert v-else title="该团队暂未获奖" type="info" :closable="false" show-icon>
              </el-alert>
            </div>

            <!-- 奖金分配按钮 -->
            <div class="bonus-actions" v-if="bonusData.award_status === '已获奖' && hasManagementPermission">
              <el-button type="success" icon="el-icon-money" @click="handleDistributeBonus" :loading="distributeLoading"
                size="medium" class="distribute-btn">
                一键分配奖金
              </el-button>
              <el-button type="primary" icon="el-icon-edit" @click="handleManualDistributeBonus" size="medium">
                手动分配奖金
              </el-button>
              <el-button type="warning" icon="el-icon-refresh" @click="handleResetTeamBonus"
                :loading="resetBonusLoading" size="medium" class="reset-btn">
                重置团队奖金
              </el-button>
              <div class="bonus-tips">
                将按照规则自动分配奖金给团队成员
              </div>
            </div>

            <!-- 无权限时的提示 -->
            <div v-else-if="bonusData.award_status === '已获奖' && hasManagementPermission === false"
              class="no-permission-actions">
              <el-alert title="只有第一位指导老师可以进行奖金分配操作" type="info" :closable="false" show-icon>
              </el-alert>
            </div>
          </div>
        </div>

        <div class="member-list-section">
          <!-- 区域标题栏 -->
          <div class="section-header">
            <h4 class="section-title">团队成员列表</h4>
            <div class="member-count">共 {{ memberList.length }} 名成员</div>
          </div>

          <!-- 成员数据表格 -->
          <el-table :data="memberList" v-loading="memberLoading" class="member-table" empty-text="暂无团队成员" border stripe>

            <!-- 用户ID列 -->
            <el-table-column label="用户ID" align="center" prop="userId" width="80" />

            <!-- 成员姓名列 -->
            <el-table-column label="成员姓名" align="center" prop="nickName" width="120" />

            <!-- 成员类型列 -->
            <el-table-column label="成员类型" align="center" prop="teamType" width="120">
              <template slot-scope="scope">
                <el-tag :type="getMemberTypeTagType(scope.row.teamType)" class="member-type-tag"
                  :class="{ 'readonly-tag': !hasManagementPermission }"
                  @click="hasManagementPermission && handleEditMemberType(scope.row)">
                  {{ getMemberTypeLabel(scope.row.teamType) }}
                  <span v-if="scope.row.isFirstInstructor" class="first-instructor-badge">(第一位)</span>
                </el-tag>
              </template>
            </el-table-column>

            <!-- 分配奖金列 -->
            <el-table-column label="分配奖金" align="center" prop="money" width="120">
              <template slot-scope="scope">
                <div class="bonus-amount-display" :class="{
                  'has-bonus': scope.row.money && scope.row.money > 0,
                  'readonly-bonus': !hasManagementPermission
                }" @click="hasManagementPermission && handleEditBonus(scope.row)">
                  <span v-if="scope.row.money && scope.row.money > 0">
                    ¥{{ scope.row.money }}
                  </span>
                  <span v-else class="no-bonus">
                    暂未分配
                  </span>
                </div>
              </template>
            </el-table-column>

            <!-- 操作列 -->
            <el-table-column label="操作" align="center" width="450" class-name="action-column">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit"
                  @click="hasManagementPermission && handleEditBonus(scope.row)" :disabled="!hasManagementPermission"
                  class="action-btn">
                  修改奖金
                </el-button>
                <el-button size="mini" type="text" icon="el-icon-user"
                  @click="hasManagementPermission && handleEditMemberType(scope.row)"
                  :disabled="!hasManagementPermission" class="action-btn">
                  更改类型
                </el-button>
                <el-button size="mini" type="text" icon="el-icon-refresh"
                  @click="hasManagementPermission && handleResetMemberBonus(scope.row)"
                  :disabled="!hasManagementPermission" class="action-btn reset-btn">
                  重置奖金
                </el-button>
                <el-button size="mini" type="text" icon="el-icon-delete"
                  @click="hasManagementPermission && handleRemoveMember(scope.row)"
                  :disabled="!hasManagementPermission || scope.row.isFirstInstructor" class="action-btn delete-btn">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 添加成员区域 -->
        <div class="add-member-section" v-if="hasManagementPermission">
          <div class="section-header">
            <h4 class="section-title">添加团队成员</h4>
          </div>
          <el-form :model="addMemberForm" :inline="true" class="add-member-form" label-width="100px">
            <el-form-item label="选择成员" prop="userId">
              <el-select v-model="addMemberForm.userId" placeholder="请选择成员" filterable clearable class="member-select"
                :loading="userLoading">
                <el-option v-for="user in availableUsers" :key="user.userId"
                  :label="user.nickName + ' (' + user.userName + ')'" :value="user.userId" />
              </el-select>
            </el-form-item>
            <el-form-item label="成员类型" prop="teamType">
              <el-select v-model="addMemberForm.teamType" placeholder="请选择类型" class="type-select">
                <el-option label="指导老师" :value="111" />
                <el-option label="参赛选手" :value="112" />
              </el-select>
            </el-form-item>
            <el-form-item class="add-btn-item">
              <el-button type="primary" @click="handleAddMember" :loading="addMemberLoading" class="add-btn">
                添加成员
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 无权限时的添加成员提示 -->
        <div v-else class="add-member-section readonly-section">
          <div class="section-header">
            <h4 class="section-title">添加团队成员</h4>
          </div>
          <el-alert title="只有第一位指导老师可以添加团队成员" type="info" :closable="false" show-icon>
          </el-alert>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="membersOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 修改成员类型对话框 -->
    <el-dialog title="更改成员类型" :visible.sync="memberTypeOpen" width="400px" append-to-body>
      <el-form ref="memberTypeForm" :model="memberTypeForm" :rules="memberTypeRules" label-width="80px">
        <el-form-item label="团队成员" prop="nickName">
          <el-input v-model="memberTypeForm.nickName" disabled />
        </el-form-item>
        <el-form-item label="成员类型" prop="teamType">
          <el-select v-model="memberTypeForm.teamType" placeholder="请选择成员类型" style="width: 100%">
            <el-option label="指导老师" :value="111" />
            <el-option label="参赛选手" :value="112" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMemberTypeForm" :loading="memberTypeLoading">确 定</el-button>
        <el-button @click="memberTypeOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 手动分配奖金对话框 -->
    <el-dialog title="手动分配奖金" :visible.sync="manualDistributeOpen" width="500px" append-to-body>
      <el-form ref="manualDistributeForm" :model="manualDistributeForm" :rules="manualDistributeRules"
        label-width="120px">
        <el-form-item label="指导老师奖金" prop="instructorBonus">
          <el-input-number v-model="manualDistributeForm.instructorBonus" :min="0"
            :max="bonusData ? bonusData.instructor_bonus : 0" :step="100" style="width: 200px"
            placeholder="请输入指导老师奖金" />
          <div class="form-tips">
            可分配金额: ¥{{ formatMoney(bonusData ? bonusData.instructor_bonus : 0) }}
            <span v-if="manualDistributeForm.instructorBonus > (bonusData ? bonusData.instructor_bonus : 0)"
              class="amount-warning">
              (超出可分配金额)
            </span>
          </div>
        </el-form-item>
        <el-form-item label="参赛选手奖金" prop="participantBonus">
          <el-input-number v-model="manualDistributeForm.participantBonus" :min="0"
            :max="bonusData ? bonusData.participant_bonus : 0" :step="100" style="width: 200px"
            placeholder="请输入参赛选手奖金" />
          <div class="form-tips">
            可分配金额: ¥{{ formatMoney(bonusData ? bonusData.participant_bonus : 0) }}
            <span v-if="manualDistributeForm.participantBonus > (bonusData ? bonusData.participant_bonus : 0)"
              class="amount-warning">
              (超出可分配金额)
            </span>
          </div>
        </el-form-item>
        <el-form-item label="总奖金">
          <div class="total-bonus-display">
            ¥{{ formatMoney(manualDistributeForm.instructorBonus + manualDistributeForm.participantBonus) }}
            <span class="total-tips">
              / 可分配总额: ¥{{ formatMoney((bonusData ? bonusData.instructor_bonus : 0) + (bonusData ?
                bonusData.participant_bonus : 0)) }}
            </span>
            <span v-if="(manualDistributeForm.instructorBonus + manualDistributeForm.participantBonus) >
              ((bonusData ? bonusData.instructor_bonus : 0) + (bonusData ? bonusData.participant_bonus : 0))"
              class="amount-warning">
              (超出可分配总额)
            </span>
          </div>
        </el-form-item>
        <el-form-item label="分配说明">
          <el-input type="textarea" v-model="manualDistributeForm.remark" placeholder="请输入分配说明（可选）" :rows="3"
            style="width: 300px" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitManualDistribute" :loading="manualDistributeLoading">确 定</el-button>
        <el-button @click="manualDistributeOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTeam,
  getTeam,
  delTeam,
  addTeam,
  updateTeam,
  exportTeam,
  getTeamMembers,
  addTeamMember,
  updateTeamMember,
  deleteTeamMember,
  getDistributableBonusInfo,
  distributeBonus,
  manualDistributeBonus,
  getDistributionResult,
  checkTeamHasAward,
  getAvailableUsers,
  resetTeamBonus,
  resetMemberBonus,
  checkTeamPermission
} from "@/api/commgr/team";

export default {
  name: "Team",
  data() {
    return {
      // 遮罩层
      loading: true,
      memberLoading: false,
      userLoading: false,
      addMemberLoading: false,
      bonusLoading: false,
      memberTypeLoading: false,
      distributeLoading: false,
      manualDistributeLoading: false,
      resetBonusLoading: false,
      permissionLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 团队表格数据
      teamList: [],
      // 当前团队
      currentTeam: {},
      // 成员列表
      memberList: [],
      // 奖金数据
      bonusData: null,
      // 可用用户列表
      availableUsers: [],
      // 权限相关
      hasManagementPermission: null, // null: 未检查, true: 有权限, false: 无权限
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示成员弹窗
      membersOpen: false,
      // 是否显示奖金弹窗
      bonusOpen: false,
      // 是否显示成员类型弹窗
      memberTypeOpen: false,
      // 是否显示手动分配弹窗
      manualDistributeOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        teamName: null,
      },
      // 表单参数
      form: {
        teamId: null,
        teamName: null,
      },
      // 添加成员表单
      addMemberForm: {
        userId: null,
        teamType: null
      },
      // 奖金表单
      bonusForm: {
        membersId: null,
        nickName: '',
        money: null
      },
      // 成员类型表单
      memberTypeForm: {
        membersId: null,
        nickName: '',
        teamType: null
      },
      // 手动分配表单
      manualDistributeForm: {
        instructorBonus: 0,
        participantBonus: 0,
        remark: ''
      },
      // 表单校验
      rules: {
        teamName: [
          { required: true, message: "团队名称不能为空", trigger: "blur" }
        ]
      },
      // 奖金表单校验
      bonusRules: {
        money: [
          { required: true, message: "请输入分配奖金", trigger: "blur" },
          { type: 'number', min: 0, message: "奖金不能为负数", trigger: "blur" }
        ]
      },
      // 成员类型表单校验
      memberTypeRules: {
        teamType: [
          { required: true, message: "请选择成员类型", trigger: "change" }
        ]
      },
      // 手动分配表单校验
      manualDistributeRules: {
        instructorBonus: [
          { required: true, message: "请输入指导老师奖金", trigger: "blur" },
          { type: 'number', min: 0, message: "奖金不能为负数", trigger: "blur" }
        ],
        participantBonus: [
          { required: true, message: "请输入参赛选手奖金", trigger: "blur" },
          { type: 'number', min: 0, message: "奖金不能为负数", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 格式化金额显示 */
    formatMoney(amount) {
      if (!amount) return '0';
      return Number(amount).toLocaleString('zh-CN');
    },

    /** 获取成员类型标签 */
    getMemberTypeLabel(teamType) {
      const typeMap = {
        '111': '指导老师',
        '112': '参赛选手',
        111: '指导老师',
        112: '参赛选手',
      };
      return typeMap[teamType] || '未知类型';
    },

    /** 获取成员类型标签样式 */
    getMemberTypeTagType(teamType) {
      if (teamType === '111' || teamType === 111) {
        return 'success';
      } else if (teamType === '112' || teamType === 112) {
        return 'primary';
      }
      return 'info';
    },

    /** 查询团队列表 */
    getList() {
      this.loading = true;
      listTeam(this.queryParams).then((response) => {
        this.teamList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        this.loading = false;
        console.error('获取团队列表失败:', error);
        this.$modal.msgError("获取团队列表失败");
      });
    },

    /** 查看团队成员 */
    async handleViewMembers(row) {
      this.currentTeam = row;
      this.membersOpen = true;

      // 重置权限状态
      this.hasManagementPermission = null;

      // 首先检查权限
      await this.checkPermission(row.teamId);

      // 然后加载数据
      this.loadTeamMembers(row.teamId);
      this.loadTeamBonusInfo(row.teamId);

      // 只有有权限时才加载可用用户列表
      if (this.hasManagementPermission) {
        this.loadAvailableUsers();
      }
    },

    /** 检查团队管理权限 */
    async checkPermission(teamId) {
      this.permissionLoading = true;
      try {
        const response = await checkTeamPermission(teamId);
        this.hasManagementPermission = response.data.hasPermission;

        if (!this.hasManagementPermission) {
          this.$modal.msgWarning("您不是该团队的第一位指导老师，只有查看权限");
        }
      } catch (error) {
        console.error('检查权限失败:', error);
        this.hasManagementPermission = false;
        this.$modal.msgError("权限检查失败");
      } finally {
        this.permissionLoading = false;
      }
    },

    /** 加载团队成员 */
    loadTeamMembers(teamId) {
      this.memberLoading = true;
      getTeamMembers(teamId).then(response => {
        let members = response.data || response.rows || [];

        // 标记第一位指导老师
        let firstInstructorFound = false;
        members = members.map(member => {
          const isFirstInstructor = !firstInstructorFound && member.teamType === 111;
          if (isFirstInstructor) {
            firstInstructorFound = true;
          }
          return {
            ...member,
            isFirstInstructor: isFirstInstructor
          };
        });

        this.memberList = members;
        this.memberLoading = false;
      }).catch(error => {
        this.memberLoading = false;
        console.error('加载团队成员失败:', error);
        this.$modal.msgError("加载团队成员失败");
      });
    },

    /** 加载团队奖金信息 */
    loadTeamBonusInfo(teamId) {
      getDistributableBonusInfo(teamId).then(response => {
        this.bonusData = response.data;
        // 初始化手动分配表单
        if (this.bonusData) {
          this.manualDistributeForm.instructorBonus = this.bonusData.instructor_bonus || 0;
          this.manualDistributeForm.participantBonus = this.bonusData.participant_bonus || 0;
        }
      }).catch(error => {
        console.error('加载团队奖金信息失败:', error);
        this.bonusData = null;
      });
    },

    /** 加载可用用户 */
    loadAvailableUsers() {
      this.userLoading = true;
      getAvailableUsers().then(response => {
        this.availableUsers = response.data || response.rows || [];
        this.userLoading = false;
      }).catch(error => {
        this.userLoading = false;
        console.error('加载用户列表失败:', error);
        this.$modal.msgError("加载用户列表失败");
      });
    },

    /** 一键分配奖金 */
    handleDistributeBonus() {
      if (!this.hasManagementPermission) {
        this.$modal.msgWarning("您没有权限进行奖金分配操作");
        return;
      }

      this.$modal.confirm(`是否确认按照规则分配奖金？<br>
        指导老师：¥${this.formatMoney(this.bonusData.instructor_bonus)}<br>
        参赛选手：¥${this.formatMoney(this.bonusData.participant_bonus)}`).then(() => {
        this.distributeLoading = true;

        distributeBonus(this.currentTeam.teamId).then(response => {
          this.$modal.msgSuccess(response.msg || "奖金分配成功");
          this.distributeLoading = false;
          this.loadTeamMembers(this.currentTeam.teamId); // 刷新成员列表
          this.loadDistributionResult(); // 加载分配结果
        }).catch(error => {
          this.distributeLoading = false;
          console.error('分配奖金失败:', error);
          this.$modal.msgError("分配奖金失败: " + (error.msg || error.message || '未知错误'));
        });
      }).catch(() => {
        this.distributeLoading = false;
      });
    },

    /** 手动分配奖金 */
    handleManualDistributeBonus() {
      if (!this.hasManagementPermission) {
        this.$modal.msgWarning("您没有权限进行手动奖金分配操作");
        return;
      }
      this.manualDistributeOpen = true;
    },

    /** 提交手动分配 */
    submitManualDistribute() {
      if (!this.hasManagementPermission) {
        this.$modal.msgWarning("您没有权限进行手动奖金分配操作");
        return;
      }

      this.$refs["manualDistributeForm"].validate(valid => {
        if (valid) {
          // 验证金额是否超过可分配金额
          const instructorBonus = this.manualDistributeForm.instructorBonus;
          const participantBonus = this.manualDistributeForm.participantBonus;
          const maxInstructorBonus = this.bonusData.instructor_bonus || 0;
          const maxParticipantBonus = this.bonusData.participant_bonus || 0;

          // 验证指导老师奖金
          if (instructorBonus > maxInstructorBonus) {
            this.$modal.msgError(`指导老师奖金不能超过可分配金额 ¥${this.formatMoney(maxInstructorBonus)}`);
            return;
          }

          // 验证参赛选手奖金
          if (participantBonus > maxParticipantBonus) {
            this.$modal.msgError(`参赛选手奖金不能超过可分配金额 ¥${this.formatMoney(maxParticipantBonus)}`);
            return;
          }

          // 验证总奖金
          const totalBonus = instructorBonus + participantBonus;
          const maxTotalBonus = maxInstructorBonus + maxParticipantBonus;
          if (totalBonus > maxTotalBonus) {
            this.$modal.msgError(`总奖金不能超过可分配总金额 ¥${this.formatMoney(maxTotalBonus)}`);
            return;
          }

          this.manualDistributeLoading = true;

          const formData = {
            instructorBonus: instructorBonus,
            participantBonus: participantBonus,
            remark: this.manualDistributeForm.remark
          };

          manualDistributeBonus(this.currentTeam.teamId, formData).then(response => {
            this.$modal.msgSuccess(response.msg || "手动奖金分配成功");
            this.manualDistributeLoading = false;
            this.manualDistributeOpen = false;
            this.loadTeamMembers(this.currentTeam.teamId); // 刷新成员列表
            this.loadDistributionResult(); // 加载分配结果
          }).catch(error => {
            this.manualDistributeLoading = false;
            console.error('手动分配奖金失败:', error);
            this.$modal.msgError("手动分配奖金失败: " + (error.msg || error.message || '未知错误'));
          });
        }
      });
    },

    /** 重置团队奖金 */
    handleResetTeamBonus() {
      if (!this.hasManagementPermission) {
        this.$modal.msgWarning("您没有权限重置团队奖金");
        return;
      }

      this.$modal.confirm('是否确认重置整个团队的奖金？<br>这将把所有团队成员的奖金设置为0。').then(() => {
        this.resetBonusLoading = true;

        resetTeamBonus(this.currentTeam.teamId).then(response => {
          this.$modal.msgSuccess(response.msg || "团队奖金重置成功");
          this.resetBonusLoading = false;
          this.loadTeamMembers(this.currentTeam.teamId); // 刷新成员列表
        }).catch(error => {
          this.resetBonusLoading = false;
          console.error('重置团队奖金失败:', error);
          this.$modal.msgError("重置团队奖金失败: " + (error.msg || error.message || '未知错误'));
        });
      }).catch(() => {
        this.resetBonusLoading = false;
      });
    },

    /** 重置单个成员奖金 */
    handleResetMemberBonus(row) {
      if (!this.hasManagementPermission) {
        this.$modal.msgWarning("您没有权限重置成员奖金");
        return;
      }

      this.$modal.confirm(`是否确认重置成员 "${row.nickName}" 的奖金？`).then(() => {
        resetMemberBonus(row.membersId).then(response => {
          this.$modal.msgSuccess(response.msg || "成员奖金重置成功");
          this.loadTeamMembers(this.currentTeam.teamId); // 刷新成员列表
        }).catch(error => {
          console.error('重置成员奖金失败:', error);
          this.$modal.msgError("重置成员奖金失败: " + (error.msg || error.message || '未知错误'));
        });
      }).catch(() => { });
    },

    /** 加载分配结果 */
    loadDistributionResult() {
      getDistributionResult(this.currentTeam.teamId).then(response => {
        // 可以在这里处理分配结果的显示
        console.log('分配结果:', response.data);
      }).catch(error => {
        console.error('加载分配结果失败:', error);
      });
    },

    /** 添加团队成员 */
    handleAddMember() {
      if (!this.hasManagementPermission) {
        this.$modal.msgWarning("您没有权限添加团队成员");
        return;
      }

      if (!this.addMemberForm.userId) {
        this.$modal.msgError("请选择要添加的成员");
        return;
      }
      if (!this.addMemberForm.teamType) {
        this.$modal.msgError("请选择成员类型");
        return;
      }

      const formData = {
        teamId: this.currentTeam.teamId,
        userId: this.addMemberForm.userId,
        teamType: this.addMemberForm.teamType
      };

      this.addMemberLoading = true;
      addTeamMember(formData).then(() => {
        this.$modal.msgSuccess("添加成功");
        this.addMemberForm.userId = null;
        this.addMemberForm.teamType = null;
        this.loadTeamMembers(this.currentTeam.teamId);
        this.getList(); // 刷新团队列表
        this.addMemberLoading = false;
      }).catch(error => {
        this.addMemberLoading = false;
        console.error('添加成员失败:', error);
        this.$modal.msgError("添加成员失败");
      });
    },

    /** 修改奖金 */
    handleEditBonus(row) {
      if (!this.hasManagementPermission) {
        this.$modal.msgWarning("您没有权限修改奖金");
        return;
      }

      this.bonusForm = {
        membersId: row.membersId,
        nickName: row.nickName,
        money: row.money || 0
      };
      this.bonusOpen = true;
    },

    /** 提交奖金修改 */
    submitBonusForm() {
      this.$refs["bonusForm"].validate(valid => {
        if (valid) {
          this.bonusLoading = true;
          const formData = {
            membersId: this.bonusForm.membersId,
            money: this.bonusForm.money
          };

          updateTeamMember(formData).then(() => {
            this.$modal.msgSuccess("修改成功");
            this.bonusOpen = false;
            this.bonusLoading = false;
            this.loadTeamMembers(this.currentTeam.teamId);
          }).catch(error => {
            this.bonusLoading = false;
            console.error('修改奖金失败:', error);
            this.$modal.msgError("修改奖金失败");
          });
        }
      });
    },

    /** 修改成员类型 */
    handleEditMemberType(row) {
      if (!this.hasManagementPermission) {
        this.$modal.msgWarning("您没有权限修改成员类型");
        return;
      }

      this.memberTypeForm = {
        membersId: row.membersId,
        nickName: row.nickName,
        teamType: row.teamType
      };
      this.memberTypeOpen = true;
    },

    /** 提交成员类型修改 */
    submitMemberTypeForm() {
      this.$refs["memberTypeForm"].validate(valid => {
        if (valid) {
          this.memberTypeLoading = true;
          const formData = {
            membersId: this.memberTypeForm.membersId,
            teamType: this.memberTypeForm.teamType
          };

          updateTeamMember(formData).then(() => {
            this.$modal.msgSuccess("修改成功");
            this.memberTypeOpen = false;
            this.memberTypeLoading = false;
            this.loadTeamMembers(this.currentTeam.teamId);
            this.getList(); // 刷新团队列表
          }).catch(error => {
            this.memberTypeLoading = false;
            console.error('修改成员类型失败:', error);
            this.$modal.msgError("修改成员类型失败");
          });
        }
      });
    },

    /** 删除成员 */
    handleRemoveMember(row) {
      if (!this.hasManagementPermission) {
        this.$modal.msgWarning("您没有权限删除成员");
        return;
      }

      if (row.isFirstInstructor) {
        this.$modal.msgWarning("不能删除第一位指导老师");
        return;
      }

      this.$modal.confirm('是否确认删除成员"' + row.nickName + '"?').then(() => {
        return deleteTeamMember(row.membersId);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.loadTeamMembers(this.currentTeam.teamId);
        this.getList(); // 刷新团队列表
      }).catch(() => { });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        teamId: null,
        teamName: null,
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.teamId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加团队";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const teamId = row.teamId || this.ids[0];
      getTeam(teamId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改团队";
      }).catch(error => {
        console.error('获取团队详情失败:', error);
        this.$modal.msgError("获取团队详情失败");
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.teamId != null) {
            updateTeam(this.form).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('修改团队失败:', error);
              this.$modal.msgError("修改团队失败");
            });
          } else {
            addTeam(this.form).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error('新增团队失败:', error);
              this.$modal.msgError("新增团队失败");
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const teamIds = row.teamId || this.ids;
      this.$modal.confirm('是否确认删除团队编号为"' + teamIds + '"的数据项？').then(() => {
        return delTeam(teamIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有团队数据项？').then(() => {
        this.download('commgr/team/export', {
          ...queryParams
        }, `team_${new Date().getTime()}.xlsx`)
      }).catch(() => { });
    },
  },
};
</script>

<style scoped>
.form-tips {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.amount-warning {
  color: #F56C6C;
  font-weight: bold;
}

.total-bonus-display {
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.total-tips {
  font-size: 12px;
  color: #909399;
  margin-left: 8px;
  font-weight: normal;
}

.team-detail {
  padding: 10px;
}

.team-header {
  text-align: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e6e6e6;
}

.team-header h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 18px;
}

/* 权限相关样式 */
.permission-alert {
  margin-bottom: 20px;
}

.permission-info {
  margin-bottom: 15px;
  text-align: center;
}

.permission-tips {
  margin-left: 10px;
  color: #E6A23C;
  font-size: 14px;
}

.no-permission-actions {
  margin-top: 20px;
}

.readonly-section {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  opacity: 0.7;
}

.readonly-tag {
  cursor: default !important;
}

.readonly-tag:hover {
  opacity: 1 !important;
  transform: none !important;
}

.readonly-bonus {
  cursor: default !important;
}

.readonly-bonus:hover {
  background-color: transparent !important;
}

.first-instructor-badge {
  font-size: 10px;
  color: #67C23A;
  margin-left: 2px;
}

/* 禁用状态的按钮样式 */
.action-btn.is-disabled {
  color: #C0C4CC !important;
  cursor: not-allowed !important;
}

.action-btn.is-disabled:hover {
  color: #C0C4CC !important;
  background-color: transparent !important;
}

/* 奖金信息样式 */
.bonus-info {
  margin-top: 15px;
}

.bonus-cards {
  margin-bottom: 15px;
}

.bonus-card {
  border-radius: 8px;
  border: none;
}

.bonus-card-content {
  text-align: center;
  padding: 15px 10px;
}

.bonus-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.bonus-amount {
  font-size: 20px;
  font-weight: bold;
}

.award-info {
  margin-top: 10px;
}

.member-list-section {
  margin-bottom: 20px;
}

.member-list-section h4 {
  margin-bottom: 15px;
  color: #333;
  font-size: 16px;
}

.add-member-section {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
}

.add-member-section h4 {
  margin-bottom: 15px;
  color: #333;
  font-size: 16px;
}

.text-muted {
  color: #909399;
}

.member-item {
  margin: 2px 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

/* 对话框样式 */
.team-members-dialog {
  border-radius: 8px;
}

.team-detail {
  padding: 0;
}

/* 团队头部样式 */
.team-header {
  text-align: center;
  margin-bottom: 24px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.team-title {
  margin: 0 0 20px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

/* 奖金信息样式 */
.bonus-info {
  margin-top: 16px;
}

.bonus-cards {
  margin-bottom: 16px;
}

.bonus-card {
  border-radius: 8px;
  border: 1px solid #e6e6e6;
  transition: all 0.3s ease;
}

.bonus-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.bonus-card-content {
  text-align: center;
  padding: 20px 15px;
}

.bonus-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  font-weight: 500;
}

.bonus-amount {
  font-size: 22px;
  font-weight: 700;
}

.instructor-color {
  color: #67C23A;
}

.participant-color {
  color: #409EFF;
}

.total-color {
  color: #E6A23C;
}

/* 获奖信息样式 */
.award-info {
  margin: 16px 0;
}

/* 奖金分配按钮样式 */
.bonus-actions {
  margin-top: 20px;
  text-align: center;
}

.distribute-btn {
  padding: 10px 24px;
  font-size: 14px;
}

.reset-btn {
  /* background-color: #E6A23C;
  border-color: #E6A23C; */
  /* border-color: #e6a23c; */

}

.reset-btn:hover {
  /* background-color: #e6a23c; */
  color: #fff;
  opacity: 0.8;
}

.bonus-tips {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

/* 成员列表区域样式 */
.member-list-section {
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-title {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.member-count {
  color: #909399;
  font-size: 14px;
}

.member-table {
  width: 100%;
  margin-bottom: 0;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.member-type-tag {
  cursor: pointer;
  transition: all 0.3s ease;
}

.member-type-tag:hover {
  opacity: 0.8;
  transform: scale(1.05);
}

.bonus-amount-display {
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.bonus-amount-display:hover {
  background-color: #f5f7fa;
}

.bonus-amount-display.has-bonus {
  /* color: #E6A23C; */
  font-weight: 600;
}

.bonus-amount-display .no-bonus {
  color: #C0C4CC;
}

/* 操作按钮样式 */
.action-column {
  padding: 8px 0;
}

.action-btn {
  margin: 0 2px;
  padding: 4px 8px;
}

.action-btn.reset-btn {
  /* color: #E6A23C; */
}

.action-btn.reset-btn:hover {
  color: #e6a23c;
  opacity: 0.8;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
}

/* 添加成员区域样式 */
.add-member-section {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
  border: 1px solid #e9ecef;
}

.add-member-form {
  display: flex;
  align-items: flex-end;
  gap: 16px;
}

.member-select {
  width: 200px;
}

.type-select {
  width: 150px;
}

.add-btn-item {
  margin-bottom: 0;
}

.add-btn {
  padding: 9px 20px;
}

/* 对话框底部样式 */
.dialog-footer {
  text-align: right;
  padding: 16px 0 0 0;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-member-form {
    flex-direction: column;
    align-items: stretch;
  }

  .member-select,
  .type-select {
    width: 100%;
  }

  .add-btn-item {
    text-align: center;
  }
}
</style>
